import Point from "./Point"

export default class Vec2 extends Point {

    static fromPoint(point: Point) {
        return new Vec2(point.x, point.y)
    }

    static fromValue(x: number, y: number) {
        return new Vec2(x, y)
    }

    /**
     * 获取 长度的平方
     */
    distance(target: Point) {
        return Math.pow(this.x - target.x, 2) + Math.pow(this.y - target.y, 2)
    }

    /**
     * 获取 长度
     */
    distanceReal(target: Point) {
        return Math.sqrt(this.distance(target))
    }

    /**
     * 减去
     */
    subtract(target: Point) {
        return new Vec2(this.x - target.x, this.y - target.y)
    }

    /**
     * 缩放
     */
    scale(scale: number) {
        if (scale < 0) {
            return new Vec2(0, 0)
        }
        if (scale > 1) {
            return Vec2.fromPoint(this)
        }
        return Vec2.fromValue(this.x * scale, this.y * scale)
    }

    /**
     * 规格化,转为即长度为1的向量,且方向不变
     */
    normalize() {
        var x = this.x;
        var y = this.y;
        var len = x * x + y * y;
        if (len > 0) {
            len = 1 / Math.sqrt(len);
        }
        return new Vec2(this.x * len, this.y * len)
    }
}